<script setup>
import { ref, watch, onMounted } from "vue";
import axios from 'axios';
import { queryClazzApi, addClazzApi, queryByIdApi, updateClazzApi, deleteClazzApi } from '@/api/clazz.js';
import { queryAllApi as queryAllEmpApi } from "@/api/emp.js";
import { ElMessage, ElMessageBox } from "element-plus";

//学科列表数据
const subjects = ref([{ name: 'Java', value: 1 }, { name: '前端', value: 2 }, { name: '嵌入式', value: 3 }, { name: '大数据', value: 4 }, { name: 'Python', value: 5 }, { name: 'Go', value: 6 }])
//员工列表数据
const emps = ref([]);

//查询全部的员工数据
const queryAllEmp = async () => {
  const result = await queryAllEmpApi();
  if (result.code) {
    emps.value = result.data;
  }
}

//搜索框
const searchClazz = ref({
  name: '',
  date: [],
  begin: '',
  end: ''
})

//查询
const search = async () => {
  const result = await queryClazzApi(searchClazz.value.name,
    searchClazz.value.begin,
    searchClazz.value.end,
    currentPage.value,
    pageSize.value);
  if (result.code) {
    clazzList.value = result.data.rows;
    total.value = result.data.total;
  }
}

//清空
const clear = () => {
  searchClazz.value = { name: '', date: [], begin: '', end: '' };
  search();
}

//watch侦听 - searchClazz的data属性
watch(() => searchClazz.value.date, (newVal, oldVal) => {
  if (searchClazz.value.date && searchClazz.value.date.length > 0) {
    searchClazz.value.begin = searchClazz.value.date[0];
    searchClazz.value.end = searchClazz.value.date[1];
  } else {
    searchClazz.value.begin = '';
    searchClazz.value.end = '';
  }
})

//定义数据模型 - 列表展示
const clazzList = ref([])

//钩子函数
onMounted(() => {
  search();
  queryAllEmp();
})

//分页配置
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const handleSizeChange = (val) => {
  search();
}

const handleCurrentChange = (val) => {
  search();
}

//新增/修改表单
const clazzs = ref({
  name: '',
  room: '',
  beginDate: '',
  endDate: '',
  masterId: '',
  subject: ''
})

//控制弹窗
const dialogFormVisible = ref(false)
const diglogTitle = ref()

//新增班级add按钮
const add = () => {
  dialogFormVisible.value = 'true';
  diglogTitle.value = '新增班级';
  //清空表单内容
  clazzs.value = {
    name: '',
    room: '',
    beginDate: '',
    endDate: '',
    masterId: '',
    subject: ''
  }
  //重置表单校验信息 resetFields()
  if (clazzFormRef.value) {
    clazzFormRef.value.resetFields()
  }
}

//保存班级信息
const save = async () => {
  // 保存之前，先校验表单，校验通过，再发送请求
  if (!clazzFormRef) return
  await clazzFormRef.value.validate(async valid => {
    if (valid) { //校验通过
      //判断是否有id，如果有id，执行修改
      let result;
      if (clazzs.value.id) {
        result = await updateClazzApi(clazzs.value)
      } else {
        result = await addClazzApi(clazzs.value);
      }
      if (result.code) { //成功
        dialogFormVisible.value = false;
        ElMessage.success('保存成功');
        search();
      } else {
        ElMessage.error(result.msg);
      }
    } else {
      ElMessage.error('表单校验不通过，请检查表单');
    }
  })
}

//定义表单校验规则
const clazzFormRef = ref();
const rules = ref({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 4, max: 30, message: '班级名称的长度应在4到30个字符之间', trigger: 'blur' },
  ],
  beginDate: [
    {
      type: 'date',
      required: true,
      message: '请选择开课时间',
      trigger: 'change',
    },
  ],
  endDate: [
    {
      type: 'date',
      required: true,
      message: '请选择结课时间',
      trigger: 'change',
    },
  ],
  subject: [
    {
      required: true,
      message: '请选择学科',
      trigger: 'change',
    },
  ],
})

//编辑
const edit = async (id) => {
  const result = await queryByIdApi(id);
  //重置表单校验信息 resetFields()
  if (clazzFormRef.value) {
    clazzFormRef.value.resetFields()
  }
  if (result.code) {
    dialogFormVisible.value = true;
    diglogTitle.value = '修改班级';
    clazzs.value = result.data;
  } else {
    ElMessage.error(result.msg)
  }
}

//删除
const deleteById = (id) => {
  ElMessageBox.confirm('您确定要删除该数据吗？', '提示',
    { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }
  ).then(async () => { //确认
    const result = await deleteClazzApi(id);
    if (result.code) {
      ElMessage.success('删除成功');
      search();
    } else {
      ElMessage.error(result.msg)
    }
  }).catch((err) => { //失败回调
    ElMessage.info('操作已取消')
  })
}

</script>

<template>
  <!-- 标题 -->
  <h1>班级管理</h1>
  <!-- 表单-搜索框 -->
  <!-- {{ searchClazz }} -->
  <div id="condition">
    <el-form :inline="true" :model="searchClazz" class="demo-form-inline">
      <el-form-item label="班级名称">
        <el-input v-model="searchClazz.name" placeholder="请输入班级名称" clearable />
      </el-form-item>
      <el-form-item label="节课时间">
        <el-date-picker v-model="searchClazz.date" type="daterange" range-separator="至" start-placeholder="开始时间"
          end-placeholder="结束时间" value-format="YYYY-MM-DD" unlink-panels="false" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 按钮 -->
  <div id="button">
    <el-button type="primary" @click="add">+ 新增班级</el-button>
  </div>

  <!-- 班级信息表格 -->
  <el-table :data="clazzList" border style="width: 100%">
    <el-table-column type="index" label="序号" width="80" align="center" />
    <el-table-column prop="name" label="班级名称" width="240" align="center" />
    <el-table-column prop="room" label="班级教室" width="100" align="center" />
    <el-table-column prop="masterName" label="班主任" width="130" align="center" />
    <el-table-column prop="beginDate" label="开课时间" width="160" align="center" />
    <el-table-column prop="endDate" label="结课时间" width="160" align="center" />
    <el-table-column prop="status" label="状态" width="160" align="center" />
    <el-table-column prop="updateTime" label="最后操作时间" width="200" align="center" />
    <el-table-column prop="address" label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页条 -->
  <div id="paging" class="pagination-container">
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40, 50, 100]" :disabled="disabled" layout="sizes, total, prev, pager, next, jumper"
      background="true" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>

  <!-- 新增/修改班级的对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="diglogTitle" width="500">
    <!-- {{ clazzs }} -->
    <el-form :model="clazzs" :rules="rules" ref="clazzFormRef">
      <el-form-item label="班级名称" label-width="100px" prop="name">
        <el-input v-model="clazzs.name" placeholder="请输入班级名称，如：西安黑马JavaEE就业100期" style="width:100%" />
      </el-form-item>
      <el-form-item label="班级教室" label-width="100px">
        <el-input v-model="clazzs.room" placeholder="请填写班级教室" />
      </el-form-item>
      <el-form-item label="开课时间" label-width="100px" prop="beginDate">
        <el-date-picker v-model="clazzs.beginDate" type="date" placeholder="请选择开课时间" style="width:100%" />
      </el-form-item>
      <el-form-item label="结课时间" label-width="100px" prop="endDate">
        <el-date-picker v-model="clazzs.endDate" type="date" placeholder="请选择结课时间" style="width:100%" />
      </el-form-item>
      <el-form-item label="班主任" label-width="100px">
        <el-select v-model="clazzs.masterId" placeholder="请选择" style="width: 100%;">
          <el-option v-for="emp in emps" :label="emp.name" :value="emp.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="学科" label-width="100px" prop="subject">
        <el-select v-model="clazzs.subject" placeholder="请选择" style="width: 100%;">
          <el-option v-for="subject in subjects" :label="subject.name" :value="subject.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer" align="center" >
        <el-button type="primary" @click="save" style="margin-right: 50px;">保存</el-button>
        <el-button type="info" @click="dialogFormVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped>
#condition {
  margin: 20px 0px;
}

#button {
  margin-bottom: 20px;
}

#paging {
  margin: 20px;
}
</style>